document.querySelector("html").style.opacity = '0';
setTimeout(function() {
	document.querySelector("html").style.opacity = '';
}, 500);

/**
 * js相对路径
 * @name jsBase
 * @type {JsBaseUrl}
 */
window.jsBase = (function() {
	var scAll = document.querySelectorAll("script"),
		thisSc = scAll[scAll.length - 1],
		thisSrc = thisSc.src;
	return thisSrc.substring(0, thisSrc.lastIndexOf('/')) + '/';
})();

/**
 * 判断浏览器
 * @name browserInfo
 * @property {Boolean} ie_ff_webkit_chrome... 判断浏览器类型
 */
window.browserInfo = (function() {
	var WIN = window,
		LOC = WIN["location"],
		NA = WIN.navigator,
		UA = NA.userAgent.toLowerCase();

	var browserInfo = {
		ie: !!(WIN.ActiveXObject || "ActiveXObject" in WIN) && ((UA.match(/msie\s(\d+)/) || [])[1] || "11"),
		ff: /firefox/.test(UA),
		chrome: /chrome/.test(UA),
		opera: /opera/.test(UA),
		safari: /apple computer/.test(UA),
		webkit: /webkit/.test(UA),
		mobile: /iphone|ipod|ipad|android|webos|blackberry|opera mini|opera mobi|iemobile/.test(UA),
		pc: !/iphone|ipod|ipad|android|webos|blackberry|opera mini|opera mobi|iemobile/.test(UA),

		windows: /windows/.test(UA),
		mac: /mac/.test(UA),
		android: /android|htc/.test(UA) || /linux/i.test(NA.platform + ''),
		ios: /iphone|ipod|ipad|ios/.test(UA),
		linux: /linux/.test(UA),

		weixin: /micromessenger/.test(UA),
		uc: /UC/.test(NA.userAgent),
		qq: /mqqbrowser/.test(UA),
	};

	return browserInfo;
})();

/*requires加载js,text,elem*/
//$.ajax({ type: "get", url: jsBase + "requires.js", async: false });
(function() {
	/*requires加载js,text,elem*/
	/**
	 * @name requires
	 * @param {URIString} url xx.js或css|xx.css或text|xx.tpl
	 * @param {Boolean|Function} [asy]
	 * @return {Promise}
	 */
	window.requires = function(url, asy) {
		if("string" != typeof url) return console.log('只接受单一地址'), !1;
		var $url = url.split('|');
		switch($url[0]) {
			case 'css':
				requires.css($url[1])
				break;
			case 'text':
				return requires.text($url[1], asy)
				break;
			default:
				return requires.js(url, asy)
		}
	};

	window.requiresObj = {};
	window.requiresTextObj = {};

	requires.js = function(url, asy) {
		var urlStr = url.replace(/http(s)?\:\/\//, '').replace(/\.|\:|\/|\-/g, '_');
		if(requiresObj[urlStr + '']) {
			return requiresObj[urlStr + '']
				.done(function() {
					($.type(asy) == 'function') && asy()
				})
				.fail(function() {
					console.error('文件' + url + '请求失败!')
				});
		} else {
			return requiresObj[urlStr + ''] = $.ajax({
					type: "get",
					url: url,
					async: asy ? true : false,
					dataType: "script",
					cache: true
				})
				.done(function() {
					($.type(asy) == 'function') && asy()
				})
				.fail(function() {
					console.error('文件' + url + '请求失败!')
				});
		}
	};

	requires.css = function(url) {
		if(!document.querySelector('[sign="' + url + '"]')) {
			var dom = document.createElement("link");
			dom.setAttribute('href', url);
			dom.setAttribute('rel', 'stylesheet');
			dom.setAttribute('type', 'text/css');
			dom.setAttribute('sign', url);
			document.getElementsByTagName('head')[0].appendChild(dom);
		}
	};

	requires.text = function(url, fn) {
		var $href = url.split('#'),
			content = '',
			$hrefSrc = $href[0],
			$hrefID = $href[1] && $href[1];
		var urlStr = $hrefSrc.replace('http://', '').replace(/\.|\:|\/|\-/g, '_');

		var successFn = function(data) {
			if($hrefID) {
				if(requiresTextObj[urlStr + '_' + $hrefID]) {
					content = requiresTextObj[urlStr + '__' + $hrefID];
				} else {
					data = data.replace(/\<\!DOCTYPE/, '<div').replace(/<(html|head|body)/g, '<div').replace(/<\/(html|head|body)/g, '</div');
					var wrap = document.createElement("div");
					wrap.innerHTML = data;
					var dom = wrap.querySelector('#' + $hrefID);
					content = dom ? dom.outerHTML : '';
					requiresTextObj[urlStr + '__' + $hrefID] = content;
				}
			} else {
				content = data;
			}
		};

		if(fn) {
			if(requiresObj[urlStr + '']) {
				return requiresObj[urlStr + '']
					.done(function(data) {
						successFn(data);
						($.type(fn) == 'function') && fn(content);
					})
					.fail(function() {
						console.error('文件' + $hrefSrc + '请求失败')
					});
			} else {
				return requiresObj[urlStr + ''] = $.ajax({
						type: "get",
						url: $hrefSrc,
					})
					.done(function(data) {
						successFn(data);
						($.type(fn) == 'function') && fn(content);
					})
					.fail(function() {
						console.error('文件' + $hrefSrc + '请求失败')
					});
			}
		} else {
			if(requiresObj[urlStr + '']) {
				requiresObj[urlStr + '']
					.done(function(data) {
						successFn(data);
					})
					.fail(function() {
						console.error('文件' + $hrefSrc + '请求失败')
					});

				return content;
			} else {
				requiresObj[urlStr + ''] = $.ajax({
						type: "get",
						url: $hrefSrc,
						async: false
					})
					.done(function(data) {
						successFn(data);
					})
					.fail(function() {
						console.error('文件' + $hrefSrc + '请求失败')
					});

				return content;
			}
		}
	};

	window.imports = function() {
		var importsAll = document.querySelectorAll("imports:not([data-wl])");
		if(importsAll.length) {
			$.each(importsAll, function(i, _this) {
				_this.setAttribute('data-wl', '');
			});
			$.each(importsAll, function(i, _this) {
				var url = _this.getAttribute('href'),
					asy = _this.getAttribute('async');
				if(asy !== null) {
					requires('text|' + url, function(content) {
						var $content = $(content).addClass(_this.getAttribute('class') || '');
						$(_this).replaceWith($content);
					})
				} else {
					var $content = $(requires('text|' + url)).addClass(_this.getAttribute('class') || '');
					$(_this).replaceWith($content);
				}
			});
		};
	};

	$(function() {
		imports();
	});
})();
//console.clear();

if(document.querySelectorAll('[data-tpl]').length == 0) {
	/*异步载入UI元素模拟*/
	requires(jsBase + 'imit.js', true);
	/*表单验证*/
	requires(jsBase + 'verify.js', true);

} else {
	/*加载模板引擎*/
	requires(jsBase + "tpl.js", true).then(function() {
		requires(jsBase + 'imit.js', true);
		requires(jsBase + 'verify.js', true);
	})
};

/*重写layui-upload*/
layui.extend({
	upload2: jsBase + 'layui-upload2',
	tree2: jsBase + 'layui-tree2'
});

(function() {
	var layui_use = layui.use;
	/**
	 * layui.use改为promise式
	 * @name layui_use
	 * @param {URIString|URIString[]} url
	 * @param {Function} [fn]
	 * @return {Promise}
	 */
	layui.use = function(url, fn) {
		var o = $.Deferred();
		layui_use.call(layui, url, function() {
			fn && fn();
			o.resolve();
		})
		return o.promise();
	};
})();

/**
 * 模板引擎 
 * @name laytpl
 * @param {Id} tplDom
 * @param {Object} data
 * @param {Function} fn
 */
window.laytpl = function(tplDom, data, fn) {
	requires(jsBase + "tpl.js", function() {
		window.laytpl(tplDom, data, fn)
	})
};

/**
 * 数据表格 
 * @name dataTable
 * @param {Object} arg
 */
window.dataTable = function(arg) {
	requires(jsBase + 'imit.js?v=1');
	return dataTable(arg);
};
/*
 *文件预览 
 * */
window.previewImg = function() {
	var arg = arguments;
	$.when(layui.use(['upload2', 'element']), requires(jsBase + "upload-preview.js", true)).then(function() {
		window.previewImg.apply(null,arg);
	})
};
/**
 * 文件上传 
 * @name upload
 * @param {Object} arg
 */
window.upload = function(arg) {
	$.when(layui.use(['upload2', 'element']), requires(jsBase + "upload-preview.js", true)).then(function() {
		window.upload(arg);
	})
};

/**
 * 文件上传预览 
 * @name uploadPreview
 * @param {Object} arg
 */
window.uploadPreview = function(arg) {
	var obj = {};
	$.when(layui.use(['upload2', 'element']), requires(jsBase + "upload-preview.js", true)).then(function() {
		obj.inst = window.uploadPreview(arg).inst;
	});
	return obj;
};

//全局加入layer
var layui_open = $.when(layui.use('layer'), requires(jsBase + "layui-open2.js", true));

//局部刷新方式  total 后台获取总条数,发送给后台  pageNum 请求第几页,发送给后台  pageSize 每页几条
window.pageAjax = function(argObj) {
	$.when(layui.use('laypage'), requires(jsBase + "layui-page2.js", true), layui_open).then(function() {
		window.pageAjax(argObj);
	});
};
//刷新页面
window.pageUrl = function(argObj) {
	$.when(layui.use('laypage'), requires(jsBase + "layui-page2.js", true), layui_open).then(function() {
		window.pageUrl(argObj);
	});
};
//hash模式
window.pageHash = function(argObj) {
	$.when(layui.use('laypage'), requires(jsBase + "layui-page2.js", true), layui_open).then(function() {
		window.pageHash(argObj);
	});
};

/**   
 * json数组转树状结构   
 * @param   {json}      json数据   
 * @param   {String}    id的字符串   
 * @param   {String}    父id的字符串   
 * @param   {String}    children的字符串 
 * @param	{String}	排序的字符串
 * @return  {Array}     数组
 */
var transData = function(a, idStr, pidStr, chindrenStr, sortStr) {
	var r = [],
		hash = {},
		id = idStr,
		pid = pidStr,
		children = chindrenStr,
		i = 0,
		j = 0,
		len = a.length;
	for(; i < len; i++) {
		hash[a[i][id]] = a[i];
	}
	for(; j < len; j++) {
		var aVal = a[j],
			hashVP = hash[aVal[pid]];
		if(hashVP) {
			!hashVP[children] && (hashVP[children] = []);
			hashVP[children].push(aVal);
		} else {
			r.push(aVal);
		}
	}
	if(sortStr != undefined) {
		for(var k = 0; k < len; k++) {
			if(hash[a[k][id]][children]) {
				hash[a[k][id]][children].sort(function(n1, n2) {
					return n1[sortStr] - n2[sortStr]
				});
			}
		}
	}
	return r;
}
/**   
 * layui->tree
 */
window.tree = function(treeArg) {
	layui.use('tree2', function() {
		window.tree = layui.tree2;
		tree(treeArg);
	});
};

//tree改为table-tree
window.tableTree = function(treeArg) {
	var $view = $(treeArg.elem);
	$view.on('click', '.table-spread', function() {
		$(this).parents('li').eq(0).children('.layui-tree-spread').trigger('click');
	});
	$view.on('click', '.table-check', function() {
		$(this).parents('li').eq(0).children('.layui-tree-check').trigger('click');
	});
};

/*添加watchData监控数据变化*/
/*改进serializeArray,添加serializeObj,滚轮事件,拖拽事件*/
(function() {
	var Jsonob = (function() {
		var OP = Object.prototype,
			types = {
				obj: '[object Object]',
				array: '[object Array]'
			},
			OAM = ['push', 'pop', 'shift', 'unshift', 'short', 'reverse', 'splice'];

		var Jsonob = function(obj, cb) {
			if(OP.toString.call(obj) !== types.obj && OP.toString.call(obj) !== types.array) {
				console.log('请传入一个对象或数组');
				return false;
			}
			this._callback = cb;
			this.observe(obj);
		};
		Jsonob.prototype.observe = function(obj, path) {
			var _this = this;

			if(OP.toString.call(obj) === types.array) {
				this.overrideArrayProto(obj, path);
			}

			Object.keys(obj).forEach(function(key) {
				var oldVal = obj[key];
				var pathArray = path && path.slice();
				if(pathArray) {
					pathArray.push(key);
				} else {
					pathArray = [key];
				}
				Object.defineProperty(obj, key, {
					get: function get() {
						return oldVal;
					},
					set: function(newVal) {
						if(oldVal !== newVal) {
							if(OP.toString.call(newVal) === '[object Object]') {
								this.observe(newVal, pathArray);
							}
							this._callback(newVal, oldVal, pathArray);
							oldVal = newVal;
						}
					}.bind(_this)
				});
				if(OP.toString.call(obj[key]) === types.obj || OP.toString.call(obj[key]) === types.array) {
					_this.observe(obj[key], pathArray);
				}
			}, this);
		};

		Jsonob.prototype.overrideArrayProto = function(array, path) {
			// 保存原始 Array 原型    
			var originalProto = Array.prototype,

				// 通过 Object.create 方法创建一个对象，该对象的原型是Array.prototype    
				overrideProto = Object.create(Array.prototype),
				self = this,
				result;
			// 遍历要重写的数组方法    
			OAM.forEach(function(method) {
				Object.defineProperty(overrideProto, method, {
					value: function value() {
						var oldVal = this.slice();
						//调用原始原型上的方法    
						result = originalProto[method].apply(this, arguments);
						//继续监听新数组    
						self.observe(this, path);
						self._callback(this, oldVal, path);
						return result;
					}
				});
			});
			// 最后 让该数组实例的 __proto__ 属性指向 假的原型 overrideProto    
			array.__proto__ = overrideProto;
		};

		return Jsonob;
	})();
	var watchDom = function(dom, fn) {
		var MutationObserver = window.MutationObserver ||
			window.WebKitMutationObserver ||
			window.MozMutationObserver;

		if(!!MutationObserver) {
			var observe = new MutationObserver(function(x) {
				fn.apply(dom);
			});
			observe.observe(dom, {
				attributes: true,
				childList: true,
			});
		} else {
			dom.addEventListener("DOMSubtreeModified", function(event) {
				if(event.eventPhase == 2) {
					fn.apply(dom);
				}
			})
		}
	};

	$.extend({
		/**
		 * @name $_watchData
		 * @property {Object|Array} data
		 * @property {Function} fn
		 */
		"watchData": function(data, fn) {
			new Jsonob(data, fn)
		},
		"watchDom": function(dom, fn) {
			watchDom(dom, fn)
		}
	});

	var _serializeArray = $.fn.serializeArray;
	$.fn.extend({
		"serializeArray": function() {
			var disabled = this.find('input:disabled,select:disabled,textarea:disabled');
			disabled.each(function(i, iv) {
				iv.removeAttribute('disabled');
			});
			var _return = _serializeArray.apply(this, arguments);
			disabled.each(function(i, iv) {
				iv.setAttribute('disabled', 'disabled');
			})
			return _return
		},
		/**
		 * @name $(id)_mousewheel
		 * @property {Function} fn
		 * @example $('#box').mousewheel(function(){
		 * 	console.log(this.down)
		 * })
		 */
		'mousewheel': function(Fn) {
			if(window.browserInfo.ff) {
				$(this).on('DOMMouseScroll', function(ev) {
					ev.preventDefault();
					var oEvent = ev || event;
					this.down = (oEvent.originalEvent.detail > 0);
					Fn.apply(this);
				})
			} else {
				$(this).on('mousewheel', function(ev) {
					ev.preventDefault();
					var oEvent = ev || event;
					this.down = (oEvent.originalEvent.wheelDelta < 0);
					Fn.apply(this);
				})
			}
		},
		/**
		 * @name $(id)_move
		 * @property {Function} fn
		 * @example $('#box').move(function(){
		 * 	console.log(this.pageXc,this.pageYc)
		 * })
		 */
		'move': function(Fn) {
			$(this).on('mousedown', function(ev) {
				this.pageXc = this.pageYc = 0;
				var _this = this,
					pvrPageX = ev.pageX,
					pvrPageY = ev.pageY;
				$(document).on('mousemove.thisMove', function(ev) {
					ev.preventDefault(); //阻止选中文字
					_this.pageXc = ev.pageX - pvrPageX;
					_this.pageYc = ev.pageY - pvrPageY;
					Fn.apply(_this);
					pvrPageX = ev.pageX;
					pvrPageY = ev.pageY;
				});
				$(document).on('mouseup.thisMove', function(ev) {
					$(this).off('mousemove.thisMove mouseup.thisMove');
				});
			});
		}
	});
})();

/*//promise
var promiseDemo = function() {
	var o = $.Deferred();
	setTimeout(function() {
		if(Math.round(Math.random())) {
			console.log("success1");
			o.resolve("success1");
		} else {
			console.log("error1")
			o.reject("error1");
		}
	}, 1000);
	return o.promise();
};*/
//打开额外tab
window.tabOpenExtra || (window.tabOpenExtra = window.top.tabOpenExtra);
//tab切换 index为当前点击tab对应的index值
window.toggleTab = function(dom, index) {
	$(dom).addClass('active').siblings('li').removeClass('active')
		.parent('.m-tab-title').siblings('.m-tab-content').find('.m-tab-item').eq(index).addClass('m-show')
		.siblings('.m-tab-item').removeClass('m-show');
};